package com.xlh.imp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xlh.dao.SchoolInfoActionDao;
import com.xlh.entity.ParamSchool;
import com.xlh.entity.PlatformUser;
import com.xlh.entity.PlatformUserEntity;
import com.xlh.enums.SysEnum;
import com.xlh.param.UpdatePlatInfoParam;
import com.xlh.param.UpdatePlatUserInfoParam;
import com.xlh.service.PlatformUserService;
import com.xlh.util.PageDTO;
import com.xlh.util.UnicodeUtil;
import com.xlh.util.UtilFile;
import com.xlh.vo.SchoolInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component("SchoolInfoActionImpl")
public class SchoolInfoActionImpl {
    @Autowired
    private SchoolInfoActionDao schoolInfoActionDao;

    @Autowired
    private PlatformUserService platformUserService;


    @Autowired
    private UtilFile utilFile;

    public PageDTO  querySchoolInfo(Integer pageNum, Integer pageSize, Map<String, Object> paramMap) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> list = schoolInfoActionDao.querySchoolInfo(paramMap);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(list);
        return new PageDTO<>(pageInfo);
    }
    public List<Map<String, Object>> querySaleUser(String saleId) throws Exception {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> list = schoolInfoActionDao.querySaleUser(saleId);
        return list;
    }

    public SchoolInfoVO querySchoolInfoById(String schoolName) throws Exception {

        SchoolInfoVO schoolInfoVO = new SchoolInfoVO();
        List listnew= Lists.newArrayList();
        List listnew2= Lists.newArrayList();
        List listnew3= Lists.newArrayList();
        List listnew4= Lists.newArrayList();
        List platformUserFz= Lists.newArrayList(); //仿真 用户信息
        List platformUserZl= Lists.newArrayList(); //智联 用户信息

        try {
            List<Map<String, Object>> list = schoolInfoActionDao.querySchoolInfoById(schoolName);
            List<Map<String, Object>> list2 = schoolInfoActionDao.queryPlatformUserById(schoolName);
            for (Map<String, Object> map :list2 ) {

                Integer sysCode = Integer.valueOf(map.get("system_id").toString());
                if(SysEnum.SYSJx.getCode().equals(sysCode)){
                    loadPlantUserInfos(listnew, map);
                }
                if(SysEnum.SYSSx.getCode().equals(sysCode)){
                    loadPlantUserInfos(listnew2, map);
                }
                if(SysEnum.SYSKy.getCode().equals(sysCode)){
                    loadPlantUserInfos(listnew3, map);
                }
                if(SysEnum.SYSSj.getCode().equals(sysCode)){
                    loadPlantUserInfos(listnew4, map);
                }
                if(SysEnum.SYSFz.getCode().equals(sysCode)){
                    loadPlantUserInfos(platformUserFz, map);
                }
                if(SysEnum.SYSZl.getCode().equals(sysCode)){
                    loadPlantUserInfos(platformUserZl, map);
                }
            }
            if (list!=null&&list.size()>0){
                for (Map<String, Object> map1:list) {
                    schoolInfoVO.setUrl(map1.get("url")==null?"":map1.get("url").toString());
                    schoolInfoVO.setSchool_name(map1.get("school_name")==null?"":map1.get("school_name").toString());
                    schoolInfoVO.setSale_id(map1.get("sale_id")==null?"":map1.get("sale_id").toString());
                    schoolInfoVO.setSale_phone(map1.get("sale_phone")==null?"":map1.get("sale_phone").toString());
                    schoolInfoVO.setType(map1.get("type")==null?"":map1.get("type").toString());
                }
            }
            schoolInfoVO.setTeachingAddAccounts(listnew);
            schoolInfoVO.setTrainingAddAccounts(listnew2);
            schoolInfoVO.setScientificAddAccounts(listnew3);
            schoolInfoVO.setManagementAddAccounts(listnew4);
            schoolInfoVO.setEmulatorAddAccounts(platformUserFz);
            schoolInfoVO.setMhlAddAccounts(platformUserZl);;
            schoolInfoVO.setData(list);

        } catch (Exception e) {
            throw e;
        }
        return schoolInfoVO;
    }

    /**
     * 加载平台用户信息
     * @param sysUserInfos
     * @param map
     */
    private void loadPlantUserInfos(List sysUserInfos, Map<String, Object> map) {

            Map<String, Object> userInfo = new HashMap<String, Object>();
            userInfo.put("userNum",map.get("user_number").toString());
            String role = map.get("role") == null ? "" : map.get("role").toString();
            userInfo.put("role",map.get("role")==null?"":map.get("role").toString());
            if( map.get("system_id").toString().equals(SysEnum.SYSJx.getCode().toString()) ||
                map.get("system_id").toString().equals(SysEnum.SYSSx.getCode().toString()) ||
                map.get("system_id").toString().equals(SysEnum.SYSFz.getCode().toString()) ||
                map.get("system_id").toString().equals(SysEnum.SYSZl.getCode().toString()) )
            {
                String roleName = "";
                if ("1".equals(role)){
                    roleName="教师";
                }else{
                    roleName="学生";
                }
                userInfo.put("roleName",roleName);
            }
            userInfo.put("roleId",map.get("role")==null?"":map.get("role").toString());
            userInfo.put("id", map.get("id"));
            sysUserInfos.add(userInfo);
    }

    @Transactional
    public Map<String, Object> addSchoolInfo(ParamSchool paramSchool) throws Exception {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        String url="";
        String message = checkPlatformUser(paramSchool);
        if(StrUtil.isNotBlank(message)){
            resultMap.put("data", message);
            resultMap.put("code",5001);
            return resultMap;
        }
        if(paramSchool.getSchoolName().length() > 200){
            resultMap.put("data", "学校名称不能大于200个字符");
            resultMap.put("code",5001);
            return resultMap;
        }
        Integer integer = schoolInfoActionDao.querySchoolName(paramSchool.getSchoolName());
        if (integer>0){
            resultMap.put("data", "学校名称重复");
            resultMap.put("code",5001);
            return resultMap;
        }
        url= StringUtils.join(utilFile.getServerAddress(),"?saleId=", UnicodeUtil.gbEncoding(paramSchool.getSaleId()) ,"&salePhone=",paramSchool.getSalePhone(),"&schoolName=",UnicodeUtil.gbEncoding(paramSchool.getSchoolName()),"&type=",paramSchool.getType());
        if (paramSchool!=null&&paramSchool.getStutas()==1){
            resultMap.put("url", url);
            resultMap.put("code",200);
            return resultMap;
        }
        StringBuilder systemId = new StringBuilder();
        appendSystemId(paramSchool.getSystemJx(), systemId, "教学");
        appendSystemId(paramSchool.getSystemSx(), systemId, "实训");
        appendSystemId(paramSchool.getSystemKy(), systemId, "科研");
        appendSystemId(paramSchool.getSystemSj(), systemId, "数据");
        appendSystemId(paramSchool.getSystemFz(), systemId, "仿真");
        appendSystemId(paramSchool.getSystemZl(), systemId, "智联");

        paramSchool.setUrl(url);
        paramSchool.setSystemId(systemId.toString());
        schoolInfoActionDao.addSchoolInfo(paramSchool);
        saveSchoolInfo(paramSchool.getSystemJx(),SysEnum.SYSJx.getCode(),paramSchool.getSchoolName());
        saveSchoolInfo(paramSchool.getSystemSx(),SysEnum.SYSSx.getCode(),paramSchool.getSchoolName());
        saveSchoolInfo(paramSchool.getSystemKy(),SysEnum.SYSKy.getCode(),paramSchool.getSchoolName());
        saveSchoolInfo(paramSchool.getSystemSj(),SysEnum.SYSSj.getCode(),paramSchool.getSchoolName());
        saveSchoolInfo(paramSchool.getSystemFz(),SysEnum.SYSFz.getCode(),paramSchool.getSchoolName());
        saveSchoolInfo(paramSchool.getSystemZl(),SysEnum.SYSZl.getCode(),paramSchool.getSchoolName());

        resultMap.put("code",200);
        return resultMap;
    }

    /**
     * 检查平台用户是否合规
     * @param paramSchool
     * @return
     */
    private String checkPlatformUser(ParamSchool paramSchool) throws Exception {

        List<PlatformUser> allPlatformUser = getPlatformUsers(paramSchool);
        if(CollectionUtil.isEmpty(allPlatformUser)){
            throw new Exception("用户信息不能为空！");
        }
        for (PlatformUser platformUser : allPlatformUser) {

            if(platformUser.getUserNum().length() > 20){
                return "账号长度必须小于20位";
            }
        }
        return null;
    }

    /**
     * 追加 systemID
     * @param proxyList
     * @param systemId
     */
    private void appendSystemId(List<PlatformUser> proxyList, StringBuilder systemId, String sysName) {

        if(CollectionUtil.isEmpty(proxyList)){
            return;
        }
        if (systemId.length() > 0){
            if (!"".equals(proxyList.get(0).getUserNum()) && proxyList.get(0).getUserNum() != null){
                systemId.append("," + sysName);
            }
        }else{
            systemId.append(sysName);
        }
    }

    private  void  saveSchoolInfo(List<PlatformUser> platformUsers, Integer systemId, String school) throws Exception {

        if (platformUsers!=null&&platformUsers.size()>0) {
            for (PlatformUser platformUser: platformUsers) {
                if (!"".equals(platformUser.getUserNum())){
                    platformUser.setSystemId(systemId);
                    platformUser.setSchool(school);
                    schoolInfoActionDao.addPlatformUser(platformUser);
                }
            }
        }
    }

    /**
     * 保存用户信息
     * @param paramSchool
     */
    @Transactional
    public void savePlatformUserInfo(ParamSchool paramSchool) throws Exception {

        // 校验信息
        if(paramSchool == null || StrUtil.isBlank(paramSchool.getSchoolName())){
            throw new Exception("学院名称不能为空");
        }
        if(paramSchool.getSchoolName().length() > 200){
            throw new Exception("学校名称不能大于200个字符");
        }
        String school = paramSchool.getSchoolName();
        List<PlatformUser> allPlatformUser = getPlatformUsers(paramSchool);
        String message = checkPlatformUser(paramSchool);
        if(StrUtil.isNotBlank(message)){
            throw new Exception(message);
        }

        // 执行插入操作
        List<Integer> updateIds = allPlatformUser.stream().filter(platformUser -> ObjectUtil.isNotNull(platformUser.getId())).map(platformUser ->  platformUser.getId().intValue()).collect(Collectors.toList());
        QueryWrapper<PlatformUserEntity> wapper = new QueryWrapper<>();
        List<PlatformUserEntity> list = platformUserService.list(wapper.lambda().eq(PlatformUserEntity::getSchool, school));
        List<Integer> databaseRecordIds = list.stream()
                .map(PlatformUserEntity::getId).filter(id -> ObjectUtil.isNotNull(id)).collect(Collectors.toList());
        List<Integer> removeIds = databaseRecordIds.stream()
                .filter(databaseRecordId -> updateIds.contains(databaseRecordId) == false).collect(Collectors.toList());
        platformUserService.removeByIds(removeIds);
        List<PlatformUserEntity> saveResult = Lists.newArrayList();
        for (PlatformUser platformUser : allPlatformUser) {

            if(ObjectUtil.isNotNull(platformUser) && StrUtil.isNotBlank(platformUser.getUserNum())){
                PlatformUserEntity platformUserEntity = BeanUtil.toBean(platformUser, PlatformUserEntity.class);
                platformUserEntity.setUserNumber(platformUser.getUserNum());
                platformUserEntity.setSchool(school);
                platformUserEntity.setDate(new Date());
                saveResult.add(platformUserEntity);
            }
        }
        platformUserService.saveOrUpdateBatch(saveResult);
    }

    private List<PlatformUser> getPlatformUsers(ParamSchool paramSchool) {
        List<PlatformUser> allPlatformUser = Lists.newArrayList();
        List<PlatformUser> systemFz = paramSchool.getSystemFz();
        List<PlatformUser> systemJx = paramSchool.getSystemJx();
        List<PlatformUser> systemKy = paramSchool.getSystemKy();
        List<PlatformUser> systemSj = paramSchool.getSystemSj();
        List<PlatformUser> systemSx = paramSchool.getSystemSx();
        List<PlatformUser> systemZl = paramSchool.getSystemZl();
        if(CollectionUtil.isNotEmpty(systemFz)){
            systemFz.forEach(user -> user.setSystemId(SysEnum.SYSFz.getCode()));
            allPlatformUser.addAll(systemFz);
        }
        if(CollectionUtil.isNotEmpty(systemJx)){
            systemJx.forEach(user -> user.setSystemId(SysEnum.SYSJx.getCode()));
            allPlatformUser.addAll(systemJx);
        }
        if(CollectionUtil.isNotEmpty(systemKy)){
            systemKy.forEach(user -> user.setSystemId(SysEnum.SYSKy.getCode()));
            allPlatformUser.addAll(systemKy);
        }
        if(CollectionUtil.isNotEmpty(systemSj)){
            systemSj.forEach(user -> user.setSystemId(SysEnum.SYSSj.getCode()));
            allPlatformUser.addAll(systemSj);
        }
        if(CollectionUtil.isNotEmpty(systemSx)){
            systemSx.forEach(user -> user.setSystemId(SysEnum.SYSSx.getCode()));
            allPlatformUser.addAll(systemSx);
        }
        if(CollectionUtil.isNotEmpty(systemZl)){
            systemZl.forEach(user -> user.setSystemId(SysEnum.SYSZl.getCode()));
            allPlatformUser.addAll(systemZl);
        }
        return allPlatformUser;
    }


}
